package org.cid54.android.jshopper;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import java.util.List;
import org.cid54.android.jshopper.dao.DaoCallBackMethod;
import org.cid54.android.jshopper.dao.ItemDao;
import org.cid54.android.jshopper.dao.ShopItemDao;
import org.cid54.android.jshopper.dao.impl.ItemDaoImpl;
import org.cid54.android.jshopper.dao.impl.ShopItemDaoImpl;
import org.cid54.android.jshopper.model.ShopItem;
import org.cid54.android.jshopper.model.ShoppingList;

/**
 *
 * @author fgo
 */
public class NewShopItem extends Activity {

    public static final String SHOPPINGLIST_PARAM_NAME = "shoppingListItem";
    private final ItemDao itemDao = new ItemDaoImpl();
    private final ShopItemDao shopItemDao = new ShopItemDaoImpl();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.new_shop_item);

        this.itemDao.getAllItemNames(new DaoCallBackMethod<List<String>>() {

            public void execute(List<String> t) {
                doLayout(t);
            }
        });

    }

    private void doLayout(List<String> items) {

        final EditText amountTextBox = (EditText) this.findViewById(R.id.new_shop_item_amount_entry);
        final Spinner itemNameSpinner = (Spinner) this.findViewById(R.id.new_shop_item_product_entry);

        final ShoppingList shoppingList = (ShoppingList) this.getIntent().getExtras().get(SHOPPINGLIST_PARAM_NAME);

        ArrayAdapter<String> itemNameAdapter = new ArrayAdapter<String>(this.getApplicationContext(), android.R.layout.simple_spinner_item, items);

        itemNameAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        itemNameSpinner.setAdapter(itemNameAdapter);

        Button okButton = (Button) this.findViewById(R.id.new_shop_item_save);

        okButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {

                ShopItem shopItem = new ShopItem();

                shopItem.setAmount(Integer.parseInt(amountTextBox.getText().toString()));

                shopItem.setName(itemNameSpinner.getSelectedItem() + "");

                shopItem.setShoppingList(shoppingList);

                shopItemDao.create(shopItem, new DaoCallBackMethod<Boolean>() {

                    public void execute(Boolean t) {
                        if (t) {
                            finish();
                        }
                    }
                });
            }
        });

    }
}
